package com.edu.internship.util;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Map;

/**
 * code is far away from bug with the animal protecting
 *
 * @author lishiquan
 * @description
 * @date 2022-07-29
 */
public class DictionaryUtils {

    private DictionaryUtils() {
    }

    public static List<Map<String, Object>> getDictionary(Map<String, Object> dictionary, String dictName) {
        if (dictionary.isEmpty()) {
            return Lists.newArrayList();
        }
        return JsonUtils.getInstance().listBeanToMap((List<?>) dictionary.get(dictName));
    }

    public static String formatFromCode(String code, Map<String, Object> dictionary, String dictName) {
        try {
            List<Map<String, Object>> dictOptions = getDictionary(dictionary, dictName);
            for (Map<String, Object> dictOption : dictOptions) {
                String dictValue = Tools.defaultIfBlank((String) dictOption.get("value"), Tools.EMPTY);
                if (Tools.equals(dictValue, code)) {
                    return (String) dictOption.get("label");
                }
            }
            return code;
        } catch (Exception e) {
            return code;
        }
    }

    public static String formatFromDesc(String desc, Map<String, Object> dictionary, String dictName) {
        if (dictionary.isEmpty()) {
            return desc;
        }
        try {
            List<Map<String, Object>> dictOptions = getDictionary(dictionary, dictName);
            for (Map<String, Object> dictOption : dictOptions) {
                String dictLabel = Tools.defaultIfBlank((String) dictOption.get("label"), Tools.EMPTY);
                if (Tools.equals(dictLabel, desc)) {
                    return (String) dictOption.get("value");
                }
            }
            return desc;
        } catch (Exception e) {
            return desc;
        }
    }

    public static String formatFromDesc(String desc, Map<String, Object> dictionary, String dictName, String defaultValue) {
        String fieldCode = formatFromDesc(desc, dictionary, dictName);
        if (Tools.equals(defaultValue, fieldCode)) {
            return defaultValue;
        }
        return fieldCode;
    }
}
